// --- Copyright (c) 2006-2008 Stefan Kyntchev ---
// This software is written and copyrighted by Stefan Kyntchev 
// and BeyondPod Team members. All rights are reserved.
// Author contact: support@beyondpod.mobi
// ------------------------------------------------------------------------
// This file is part of BeyondPod RSS Feed Reader and Podcast manager
// (www.codeplex.com/BeyondPod) 
// BeyondPod is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// BeyondPod is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
//  
// You should have received a copy of the GNU General Public License
// along with BeyondPod. If not, see <http://www.gnu.org/licenses/>
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 


using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using svs.Mobile.BeyondScheduler.Core.Objects.Operations.OperationUIs;

namespace svs.Mobile.BeyondScheduler.Core.Objects.Operations
{
	public class OperationStartBeyondPodUpdate : OperationBase, IEquatable<OperationStartBeyondPodUpdate>
	{
		public const string BeyondPodHandlerCLass = "###BEYONDPOD_MESSAGE_HANDLER###";
		public const int WM_CUSTOMMSG = 0x0400;
		public static readonly Guid OperationID = new Guid("{ABC76FEC-0C02-4314-B8C4-4FEDE4C83C80}");
		public string _BeyondPodPath;
		bool _LeaveRunning = false;
		string _CategoryToUpdate = "Favorites";

		public OperationStartBeyondPodUpdate()
			: base("Start BeyondPod Update", "Start BeyondPod Update", OperationID)
		{
		}

		/// <summary>
		/// Serilized state of teh Operation
		/// </summary>
		public override string SerializedData
		{
			get { return string.Format("{0}|{1}|{2}", _CategoryToUpdate, _LeaveRunning ? "1" : "0", BeyondPodPath); }
		}


		public bool LeaveRunning
		{
			get { return _LeaveRunning; }
			set { _LeaveRunning = value; }
		}

		public string CategoryToUpdate
		{
			get { return _CategoryToUpdate; }
			set { _CategoryToUpdate = value; }
		}

		/// <summary>
		/// True if the Operation has any configuration UI
		/// </summary>
		public override bool IsConfigurable
		{
			get { return true; }
		}

		public string BeyondPodPath
		{
			get
			{
				if (_BeyondPodPath == null)
				{
					string Path1 = @"\Program Files\BeyondPod\BeyondPod.exe";
					string Path2 = @"\Storage Card\Program Files\BeyondPod\BeyondPod.exe";

					if (File.Exists(Path1))
						_BeyondPodPath = Path1;
					else if (File.Exists(Path2))
						_BeyondPodPath = Path2;
				}

				return _BeyondPodPath;
			}
			set
			{
				if (!string.IsNullOrEmpty(value) && File.Exists(value))
					_BeyondPodPath = value;
				else
					_BeyondPodPath = null;
			}
		}

		#region IEquatable<OperationStartBeyondPodUpdate> Members

		public bool Equals(OperationStartBeyondPodUpdate operationStartBeyondPodUpdate)
		{
			if (operationStartBeyondPodUpdate == null) return false;
			return true;
		}

		#endregion

		public override void Execute()
		{
			base.Execute();

			//Make sure the device does not turn off on us
			CoreHelper.SetDevicePowerState(CoreHelper.PowerState.UserIdle);

			int res = CoreHelper.PostWindowsMessage(null, BeyondPodHandlerCLass, WM_CUSTOMMSG, Owner.TaskNumber, CategoryToUpdate);

			if (res < 0)
			{
				StartBeyondPod();
			}
		}

		private void StartBeyondPod()
		{
			if (string.IsNullOrEmpty(BeyondPodPath))
			{
				CoreHelper.WriteLogEntry("Unable to execute " + _Name + " Application path does not exist!");
				return;
			}

			Process myProcess = new Process();
			try
			{
				// Get the path that stores user documents.
				myProcess.StartInfo.FileName = BeyondPodPath;
				myProcess.StartInfo.Arguments =
					string.Format("\"{0}\" {1}", string.IsNullOrEmpty(_CategoryToUpdate) ? "BPALLFEEDS" : _CategoryToUpdate, _LeaveRunning ? string.Empty : "autoexit");
				myProcess.Start();
			}
			catch (Win32Exception ex)
			{
				CoreHelper.WriteLogEntry("Unable to execute " + _Name + " Reason: " + ex.Message);
			}
		}

		/// <summary>
		/// Creates an instance of the this operation, desrialized from the serilaized string
		/// </summary>
		/// <param name="serializadData"></param>
		/// <returns></returns>
		public override OperationBase CreateInstance(string serializadData)
		{
			char[] dels = {'|'};

			string[] pars = serializadData.Split(dels);

			OperationStartBeyondPodUpdate retVal = new OperationStartBeyondPodUpdate();

			if (pars.Length > 1)
			{
				retVal._CategoryToUpdate = pars[0];
				retVal._LeaveRunning = pars[1] == "1" ? true : false;
			}

			if (pars.Length > 2)
			{
				retVal.BeyondPodPath = pars[2];
			}

			return retVal;
		}

		public override bool Equals(object obj)
		{
			if (ReferenceEquals(this, obj)) return true;
			return Equals(obj as OperationStartBeyondPodUpdate);
		}

		public override int GetHashCode()
		{
			return 0;
		}

		/// <summary>
		/// UI to configure the specific actions for thhis opertation
		/// </summary>
		public override void ShowConfigurationUI(Control parentUI)
		{
			var ui = new OperationStartBeyondPodUpdateUI();
			ui.SelectedCategory = CategoryToUpdate;

			if (ui.ShowDialog() == DialogResult.OK)
			{
				CategoryToUpdate = ui.SelectedCategory;
			}
		}
	}
}